
#include "httpfunc.h"
#include "Http.h"
#include "WiFi.h"
#include "JsonParse.h"
#include "global.h"
#include "ActionCtrl.h"
#include "CondNotice.h"

// 所有的http请求回调都在这
void onBack(String data)
{

  Serial.println(data);
  Serial.println("返回的data 长度：");
  Serial.println(data.length());

  if (isDev())
  {
    beep(true);
    delay(5);
    beep(false);
  }
  // 静态JsonDocument，用于解析JSON
  JsonDocument doc;
  DeserializationError error = deserializeJson(doc, data);
  if (error)
  {
    Serial.print(F("deserializeJson() failed: "));
    Serial.println(error.f_str());
    return;
  }

  String msg = doc["msg"];
  if (msg.equals("device_config"))
  {
    printStr("有配置数据返回");
    if (doc["data"] == nullptr)
    {
      Serial.println("返回的data==null");
      return;
    }
    String timerAction = doc["data"]["timerAction"];
    String localConfig = doc["data"]["localConfig"];
    String condNoticeList = doc["data"]["condNoticeList"];

    if (!isStringEmpty(condNoticeList))
    {
      printStr("返回的通知数据", condNoticeList);

      if (parseCondNotice(condNoticeList))
      {
        putPreferenceString("condNotice", condNoticeList);
        Serial.println("通知数据 本地保存 成功！");
      }

      // getCondNoticeList().printList();
    }

    // Serial.println(timerAction);
    // Serial.println(localConfig);

    if (!isStringEmpty(timerAction))
    {
      if (parseTimerActionString(timerAction))
      {
        putPreferenceString("timerAction", timerAction);
        Serial.println("定时任务数据 本地 保存成功");
      }
    }
    if (localConfig != NULL && !localConfig.isEmpty())
    {
      Serial.println("解析localConfig 开始 ");
      String runMode = doc["data"]["localConfig"]["typeConfig"]["runMode"];
      printStr("runMode--->", runMode);
      if (!isStringEmpty(runMode))
      {
        // 如果运行模式改变了，就需要reboot
        if (getGlobalLocalConfig()->getTypeConfig()->getRunMode() != runMode.toInt())
        {
          printStr("runMode  已改变，请求重启系统");
          setReboot(true);
        }
      }
      if (parseLocalConfigString(localConfig))
      {
        putPreferenceString("localConfig", localConfig);
        Serial.println("localConfig 保存成功");
      }
      Serial.println("解析localConfig 结束 ");
    }

    if (isReboot())
    {
      printStr("模式改变重启系统");
      delay(2000);
      ESP.restart();
    }

    return;
  }
}

// 所有的http请求回调都在这
void onBack1(String data)
{

 // Serial.println(data);
 // Serial.println("返回的data 长度：");
 // Serial.println(data.length());

 

  // if (isDev())
  // {
  //   beep(true);
  //   delay(5);
  //   beep(false);
  // }

  // 静态JsonDocument，用于解析JSON
  JsonDocument doc;
  DeserializationError error = deserializeJson(doc, data);
  if (error)
  {
    Serial.print(F("deserializeJson() failed: "));
    Serial.println(error.f_str());
    return;
  }

  String msg = doc["msg"];
  if (msg.equals("device_config"))
  {
    printStr("有配置数据返回");
    if (doc["data"] == nullptr)
    {
      Serial.println("返回的data==null");
      return;
    }

    String config = doc["data"]["config"];
    String condNoticeList = doc["data"]["condNoticeList"];
    String timerAction = doc["data"]["timerAction"];

    if (config != NULL && !config.isEmpty())
    {

      ///---------这段代码只能在这
      Serial.println("config 开始 ");
      String runMode = doc["data"]["config"]["typeConfig"]["runMode"];
      printStr("runMode--->", runMode);
      if (!isStringEmpty(runMode))
      {
        // 如果运行模式改变了，就需要reboot
        if (getGlobalLocalConfig()->getTypeConfig()->getRunMode() != runMode.toInt())
        {
          printStr("runMode  已改变，请求重启系统");
          setReboot(true);
        }
      }
      ///----------
      if (parseConfig(config))
      {
        putPreferenceString("config", config);
        printStr("config 保存成功");
      }

      setDisableLight(!getGlobalLocalConfig()->getIndicatorLight());
      setDisableBeep(!getGlobalLocalConfig()->getBeep());
    }

    if (!isStringEmpty(condNoticeList))
    {
      printStr("返回的通知数据", condNoticeList);
      if (parseCondNotice(condNoticeList))
      {
        putPreferenceString("condNotice", condNoticeList);
        Serial.println("通知数据 本地保存 成功！");
      }
      // getCondNoticeList().printList();
    }
    // Serial.println(timerAction);
    // Serial.println(localConfig);
    if (!isStringEmpty(timerAction))
    {
      if (parseTimerActionString(timerAction))
      {
        putPreferenceString("timerAction", timerAction);
        Serial.println("定时任务数据 本地 保存成功");
      }
    }

    if (isReboot())
    {
      printStr("模式改变重启系统");
      delay(1000);
      ESP.restart();
    }

    return;
  }
}

void requestActive(HttpCallBack callback, HttpCallBack error)
{

  String account = getPreferenceString("account");
  String ta = account;
  ta.concat("$smartlink2024");
  String password = encryptBase64(ta);
  JsonDocument doc;
  doc["topic"] = "active";
  doc["deviceId"] = getEspId();
  doc["account"] = account;
  doc["password"] = password;
  doc["type"] = getDeviceType();
  char json[256];
  serializeJson(doc, json, sizeof(json));
  Serial.printf(json);
  requestPost1(WEB_SERVER_URL + "/device/activeEsp8266Device", String(json), callback, error);
}

void sendData(String temp, float vcc, int vcc_pin, bool water, int waterValue)
{

  if(!isWiFiConnected()){

    return;
  }
  JsonDocument doc;
  doc["deviceId"] = getEspId();

  StaticJsonDocument<200> doc1;            // 分配200字节的静态内存给JSON文档
  JsonObject data = doc1.to<JsonObject>(); // 获取JsonObject

  data["temp"] = temp;
  data["vcc"] = vcc;
  data["vcc_pin"] = vcc_pin;
  data["water"] = water;
  data["waterValue"] = waterValue;
  data["rssi"] = getRssi();
  data["ip"] = WiFi.localIP();

  // JsonDocument<200> doc2;            // 分配200字节的静态内存给JSON文档
  // JsonArray btData = doc2.to<JsonArray>(); // 获取JsonObject

  JsonArray btData = data.createNestedArray("btValue");

  printStr("getRemoteBleMap()->size()", getRemoteBleMap()->size());
  for (int i = 0; i < getRemoteBleMap()->size(); i++)
  {
    printStr("i", i);
    RemoteBle *remoteBle = getRemoteBleMap()->getData(i);
    if (remoteBle == nullptr)
    {
      continue;
    }
    printStr("remoteBle..............");
    printStr("remoteBle", remoteBle->getRemoteAddress());
    RemoteBleData *remoteData = getRemoteBleDataMap()->get(remoteBle->getRemoteAddress());
    if (remoteData == nullptr)
    {
      continue;
    }

    JsonObject object = btData.createNestedObject();
    BTDevice *device = remoteBle->getBTDevice();
    if (device == nullptr)
    {
      continue;
    }

    List<RemoteDataBean> list = remoteData->getRemoteDataList();

    RemoteDataBean avrBean;

    float static humiValue = 0;
    float static vccValue = 0;
    long static timestamp = 0;

    list.forEach([](RemoteDataBean &bean)
                 {  
                    humiValue+  bean.getHumiValue();
                    vccValue+= bean.getVcc();
                    timestamp+=bean.getTimeStamp(); });
    avrBean.setHumiValue(humiValue / list.getSize());
    avrBean.setVcc(vccValue / list.getSize());
    avrBean.setTimeStamp(timestamp / list.getSize());

    object["address"] = device->address;
    object["name"] = device->name;
    object["nickName"] = device->nickName;
    object["value"] = getRemoteBleDataMap()->get(device->address)->getRemoteDataListStr();
    object["avrHumi"] = avrBean.getHumiValue();
    object["avrVcc"] = avrBean.getVcc();
    object["avrTS"] = avrBean.getTimeStamp();

    // btData.add(object);
    printStr("添加一条数据");
  }
  // data["sensorValue"] =
  String jsonString;
  serializeJson(data, jsonString);
  doc["data"] = jsonString;
  String jsonString1;
  serializeJson(doc, jsonString1);
  //Serial.println(jsonString1);

  Http http;
  http.setUrl(WEB_SERVER_URL + "/data/addSensorData");
  http.setData(String(jsonString1));
  http.setHttpCallBack(onBack1);

  //sendCachePost(http);
  addCachePost(http);
 // requestPost(, , onBack1);
}

 

void sendData(String temp, float humi, float weight, int solid_humi, int sun, float ntc_temp)
{
   if(!isWiFiConnected()){


    return;
  }
  JsonDocument doc;
  doc["deviceId"] = getEspId();

  StaticJsonDocument<200> doc1;            // 分配200字节的静态内存给JSON文档
  JsonObject data = doc1.to<JsonObject>(); // 获取JsonObject

  data["sht_temp"] = temp;
  data["sht_humi"] = humi;
  data["weight"] = weight;
  data["solid_humi"] = solid_humi;
  data["sun"] = sun;
  data["ntc_temp"] = ntc_temp;
  data["rssi"] = getRssi();

  String jsonString;
  serializeJson(data, jsonString);

  doc["data"] = jsonString;

  String jsonString1;
  serializeJson(doc, jsonString1);

  Serial.println(jsonString1);

  requestPost(WEB_SERVER_URL + "/data/addSensorData", String(jsonString1), onBack1);

  // publish("sensor_data",jsonString1.c_str());
}
void onBackUpgrade(String data)
{

  Serial.println("固件升级");
}
void requestUpgrade()
{
   if(!isWiFiConnected()){
    return;
  }
  JsonDocument doc;
  doc["deviceId"] = getEspId();
  String jsonString1;
  serializeJson(doc, jsonString1);

  Serial.println(jsonString1);

  requestPost(WEB_SERVER_URL + "/device/GetFirmwareUpgrade", String(jsonString1), onBackUpgrade);
}

// 消息和通知都通过此接口发送，在服务器端会区别处理
void sendNotice(ReqNotice req)
{
   if(!isWiFiConnected()){
    return;
  }

  printStr("-------------发送通知-------------------");
  if (!isSendNotice())
  {
    return;
  }
  printStr("发送通知", req.getMsg());
  JsonDocument doc;
  doc["deviceId"] = req.getDeviceId();
  doc["noticeId"] = req.getNoticeId();
  doc["msg"] = req.getMsg();
  doc["type"] = req.getType();
  doc["name"] = req.getName();
  String jsonString;
  serializeJson(doc, jsonString);

  requestPost(WEB_SERVER_URL + "/msg/notice", String(jsonString), onBack1);
}